/*
 * Copyright 2011 Seth Ladd
 * 
 * This code is adapted from Seth Ladd's +1 Button Chrome extension
 * http://blog.sethladd.com/2011/06/google-1-button-and-twitter-1-tweet.html
 * by Patrick Chanezon
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 

var addTsa = function(tweet) {
    console.log('current model: ' + prefs.id);
    if (tweet.querySelector('span.tsa')) {
        return;
    }
    var tweetText = $(tweet.querySelector('div.tweet-text')).text();
    chrome.extension.sendRequest({ "action": "classifyTweet", 
                                  "tweet": {
                                     "iso_language_code": "en",
                                     "text": tweetText}
                                  }, 
                                  function(response) {
                                    console.log('got response ' + response);
                                    //set category to tweet
                                    $(tweet).data('tsa-cat', response.category);
                                    addUi(tweet);
                                  }
                                );
    };
    
var addUi = function(tweet) {    
    var hrefSource = tweet.querySelector('a.tweet-timestamp');
    var href = 'http://twitter.com' + hrefSource.getAttribute('href').substring(3);
    var tweetId = tweet.getAttribute('data-item-id');
    var tweetText = $(tweet.querySelector('div.tweet-text')).text();
    var tsa = document.createElement('span');
    tsa.classList.add('tsa');
    $('<img/>').attr({src: chrome.extension.getURL('tsa-logo-16.png')}).appendTo($(tsa));
    prefs.categories.forEach(function(cat) {
      var category = document.createElement('a'); 
      tsa.appendChild(category);
      category.setAttribute('href', '#');
      category.appendChild(document.createTextNode(cat));
      if ($(tweet).data('tsa-cat') == cat) {
        $(category).css('color', 'blue');
      }
      $(category).click(function(event) {chrome.extension.sendRequest({ "action": "postTweet", 
                                  "tweet": {
                                     "tId": tweetId,
                                     "tLang": "en",
                                     "tHref": href,
                                     "tText": tweetText,
                                     "tCat": cat}
                                  }
                                  , function(response) {
                                      if ((response.status == 200)||(response.status == 0)) {
                                        $(event.target).css('color', 'red');
                                      } else {
                                        console.log('failed status = ' + response.status);
                                      }
                                    });
                                  }
        );
    });
    // I want to do this, but size and href aren't respected
    //plusone.innerHTML = '<div class="g-plusone" data-size="small" data-count="true" style="display:inline" data-href="' + href + '"></div>';
    var plusOneDest = tweet.querySelector('div.extra-icons');
    plusOneDest.appendChild(tsa);
};

var findTweets = function(event) {
    var node = event.target;
    if (node.webkitMatchesSelector && node.webkitMatchesSelector('div[data-item-type=tweet]')) {
        addTsa(node);
    } else if (node.querySelectorAll) {
        var tweets = node.querySelectorAll('div[data-item-type=tweet]');
        for (var i = 0; i < tweets.length; i++) {
            addTsa(tweets[i]);
        }
    }
};

var prefs = null;

var getPrefs = function(event) {
  if (!prefs) {
    chrome.extension.sendRequest({ "action": "getPrefs"}, 
                                  function(response) {
                                    console.log('got prefs ' + response);
                                    prefs = response;
                                    findTweets(event);
                                  }
                                );
  } else {
    findTweets(event);
  }
};
                                  
document.body.addEventListener("DOMNodeInserted", getPrefs, false);